package main

import (
	"awesomeProject/pb"
	"bytes"
	"encoding/binary"
	"flag"
	"github.com/gorilla/websocket"
	"google.golang.org/protobuf/proto"
	"log"
	"net/url"
)

func main() {
	var addr = flag.String("addr", "192.168.110.23:5002", "http service address")
	var conn *websocket.Conn

	req := &pb.ReqLogin{Username: "admin", Password: "admin1234"}
	u := url.URL{Scheme: "ws", Host: *addr, Path: "/game"}
	log.Printf("connecting to %s", u.String())

	conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
	if err != nil {
		log.Fatal("dial:", err)
	}
	defer conn.Close()

	go func() {

		for {
			_, message, err := conn.ReadMessage()
			if err != nil {
				log.Println("read:", err)
				return
			}

			log.Printf("收到服务器消息:")

			opCode := BytesToShort(message[:2])
			log.Println("协议号 opCode:", opCode)

			resp := &pb.RespLogin{}
			proto.Unmarshal(message[2:], resp)
			log.Println("protobuf 数据:", resp)

		}
	}()

	pbBytes, _ := proto.Marshal(req)
	opCodeBytes := ShortToBytes(1001)

	sendBytes := bytes.NewBuffer(opCodeBytes)
	sendBytes.Write(pbBytes)

	err = conn.WriteMessage(websocket.BinaryMessage, sendBytes.Bytes())
	if err != nil {
		log.Println("writeErr:", err)
		return
	}

	for {

	}
}

func ShortToBytes(n int) []byte {
	data := int16(n)
	bytebuf := bytes.NewBuffer([]byte{})
	binary.Write(bytebuf, binary.BigEndian, data)
	return bytebuf.Bytes()
}
func BytesToShort(bys []byte) int {
	bytebuff := bytes.NewBuffer(bys)
	var data int16
	binary.Read(bytebuff, binary.BigEndian, &data)
	return int(data)
}
